//
//  UIColor+Utility.m
//  DGUtilityKit
//
//  Created by Jinxiao on 12/3/13.
//  Copyright (c) 2013 debugeek. All rights reserved.
//

#import "UIColor+Utility.h"

@implementation UIColor (HexColor)

- (NSString *)hexColor
{
    if(self == [UIColor whiteColor])
    {
        return @"#ffffff";
    }
    
    CGFloat red;
    CGFloat blue;
    CGFloat green;
    CGFloat alpha;
    
    [self getRed:&red green:&green blue:&blue alpha:&alpha];
    
    int redDec = (int)(red*255);
    int greenDec = (int)(green*255);
    int blueDec = (int)(blue*255);
    
    NSString *hexColor = [NSString stringWithFormat:@"#%02x%02x%02x", (unsigned int)redDec, (unsigned int)greenDec, (unsigned int)blueDec];
    
    return hexColor;
}

+ (UIColor *)colorWithRGBHex:(NSInteger)rgbHex alpha:(CGFloat)alpha
{
    return [UIColor colorWithRed:((float)((rgbHex & 0xff0000) >> 16))/255.f green:((float)((rgbHex&0xff00) >> 8))/255.f blue:((float)(rgbHex&0xff))/255.f alpha:alpha];
}

+ (UIColor *)colorWithRGBHex:(NSInteger)rgbHex
{
    return [self colorWithRGBHex:rgbHex alpha:1.f];
}

+ (UIColor *)whiteColorWithAlpha:(CGFloat)alpha
{
    return [UIColor colorWithRGBHex:0xffffff alpha:alpha];
}

+ (UIColor *)blackColorWithAlpha:(CGFloat)alpha
{
    return [UIColor colorWithRGBHex:0x000000 alpha:alpha];
}
+ (UIColor *) colorWithHexString: (NSString *)color
{
    
    if (![color isKindOfClass:[NSString class]]||![color hasPrefix:@"#"]) {
        return [UIColor blackColor];
    }
    
    
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    // 判断前缀
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    // 从六位数值中找到RGB对应的位数并转换
    NSRange range;
    range.location = 0;
    range.length = 2;
    //R、G、B
    NSString *rString = [cString substringWithRange:range];
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}
@end
